﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace DAO
{
    public class Seguridad
    {
        public static bool ValidarUsuario(string usuario, string password)
        {
            
            SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBaseDatos"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            bool b;
            try
            {
                cn.Open();
                cmd.CommandText = "select userName,password from Usuario where userName=@User and password=@Password";
                cmd.Parameters.AddWithValue("@User", usuario);
                cmd.Parameters.AddWithValue("@Password", password);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                    b = true;
                else
                    b = false;
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error al buscar el usuario:" + ex.Message);

            }
            finally
            {
                cn.Close(); 
            }           
            return b; 
        
        }
        public static string ObtenerRoles(string usuario)
        {
            SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConexionBaseDatos"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            string rol="";
            try
            {
                cn.Open();
                cmd.CommandText = "select r.nombre from Usuario u, Rol r where userName=@User and u.id_Rol=r.id_Rol";
                cmd.Parameters.AddWithValue("@User", usuario);                
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    rol = dr["nombre"].ToString();
 
                } 
               
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error al buscar el usuario con su rol:" + ex.Message);

            }
            finally
            {
                cn.Close();
            }
            return rol; 
        }
    }
}
